package com.mindainfo.configCenter.config.dao.impl;

import com.mindainfo.configCenter.base.dao.impl.BaseDaoImpl;
import com.mindainfo.configCenter.config.bean.RemoteConfig;
import com.mindainfo.configCenter.config.dao.IRemoteConfigDao;
import org.apache.commons.lang3.StringUtils;
import org.mongodb.morphia.Datastore;
import org.mongodb.morphia.query.Query;
import org.springframework.stereotype.Repository;

import java.util.List;

/**
 * Created by MD-01 on 2016/11/14.
 */
@Repository
public class RemoteConfigDaoImpl extends BaseDaoImpl<RemoteConfig> implements IRemoteConfigDao{

    /**
     * 根据ip查询
     * @param serverHost
     * @return
     */
    public RemoteConfig getByServerHost(String serverHost){

        Datastore datastore = getDatastore();
        return datastore.createQuery(RemoteConfig.class)
                .field("serverHost").equal(serverHost)
                .get();
    }

    /**
     * 分页查询配置列表
     */
    public List<RemoteConfig> queryList(String keyword, int start, int num){

        System.err.println(keyword);
        System.err.println(start);
        System.err.println(num);

        Datastore datastore = getDatastore();
        Query<RemoteConfig> query = datastore.createQuery(RemoteConfig.class);
        if(StringUtils.isNotEmpty(keyword)){
            query = query.field("serverName").contains(keyword);
        }
        return query
                .order("-createTime")
                .offset(start).limit(num)
                .asList();
    }

    /**
     * 查询配置列表总数
     */
    public int queryListCount(String keyword){
        Datastore datastore = getDatastore();
        Query<RemoteConfig> query = datastore.createQuery(RemoteConfig.class);
        if(StringUtils.isNotEmpty(keyword)){
            query = query.field("serverName").contains(keyword);
        }
        return (int)query.countAll();
    }
}
